//
//  ST_PushPeculiaritySelectMediaController.swift
//  btvideo
//
//  Created by mac on 2020/1/13.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
//import ST_CHTCollectionViewWaterfallLayout

//发布特质选择资源 - Controller
class ST_PushPeculiaritySelectMediaController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("添加特质")
        
        view.insertSubview(collectionView, belowSubview: own_navigation_bar)
        
        collectionView.snp.makeConstraints { (make) in
            
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.left.right.bottom.equalToSuperview()
            
        }
        
        
        request_recommend_data()
    }
    
    
    
    fileprivate var current_recommend_page = 0
    
    fileprivate func request_recommend_data(){
        
        guard  let currModel = willPushPeculiarity else { return  }
        
//        current_recommend_page += 1
        
//        let param = ["page":current_recommend_page,"feature_id":currModel.id] as [String : Any]
        
        JVrequest(PH.publishExampleListApi,parameters: ["feature_id":currModel.id], success: { (json) in
            
            print("发布--推荐特质:",json)
            
          
            let aArray = json["data"].arrayValue.map { (itemJson) -> ST_ShowTraitCellModel in
                let m = ST_ShowTraitCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
            
//            if self.current_recommend_page == 1{
                self.recommend_array = aArray
//            }else{
//                self.recommend_array += aArray
//            }
            
            self.previewArray = aArray.map { (item) -> ST_MWPhoto in
                
                guard let url = item.imageUrl.big_remote_image().url , let media = ST_MWPhoto.init(url: url) else{
                    return ST_MWPhoto()
                }
                
                guard let videoUrl = item.videoUrl.url else {
                    return media
                }
                
                media.videoURL = videoUrl
                
                return media
            }
            
            
//            self.loadMoreDataStyle(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
//
//                self.request_recommend_data()
//            }
            
            self.supplementaryView?.bottom_label.isHidden = self.recommend_array.count < 1
            
            self.collectionView.reloadData()
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }
    
    
    
//    MARK:-Properties
    
    /**
     推荐特质
     */
    fileprivate lazy var recommend_array = [ST_ShowTraitCellModel]()
    
    fileprivate var previewArray = [ST_MWPhoto]()
    
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
       let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = ST_PinterestHomeCellMinimumColumnSpacing
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: 0, right: 10)
        return controlLayout
    }()
    
    fileprivate lazy var sectionheader_height:CGFloat = {
        return 552
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_ShowTraitCell.self)

        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_PushPeculiaritySelectMediaSupplementView.self)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom, right: 0)
        
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    
    fileprivate var supplementaryView:ST_PushPeculiaritySelectMediaSupplementView?
}

extension ST_PushPeculiaritySelectMediaController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return recommend_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     
        return recommend_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
            
        let cell = collectionView.dequeueReusableCell(withClass: ST_ShowTraitCell.self, for: indexPath)
        
        if let m = recommend_array[safe:indexPath.item]{
            cell.model = m
        }
        cell.max_content_number_of_lines = 2
        
        return cell
    
        
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
        
        guard let browser = ST_MWPhotoBrowser.init(photos: self.previewArray) else{
            return
        }
        
        browser.displayActionButton = false
        
        browser.setCurrentPhotoIndex(indexPath.row.uInt)
        
        let nav = UINavigationController.init(rootViewController: browser)
        
        GlobalPresent(toController: nav)
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat {
            return sectionheader_height
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
            
        if supplementaryView == nil{
            self.supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_PushPeculiaritySelectMediaSupplementView.self, for: indexPath)
            
            
            self.supplementaryView?.photo_btn_click_closure = { [weak self] in
                self?.photo_btn_click()
            }
            
            self.supplementaryView?.record_btn_click_closure = { [weak self] in
                self?.record_btn_click()
            }
        }
        return self.supplementaryView!
    }
    
    
}

//MARK: - Event

extension ST_PushPeculiaritySelectMediaController{

    fileprivate func picker_media_handle(imageType:Bool = true){
        
        let vc = ST_JVImagePickerController()
        
        if imageType{
            vc.picker_style = .image
        }else{
            vc.picker_style = .video
        }
        
        vc.overCurrentContext = true
        
        vc.picker_images_closure = {[weak self] images in
            
            let finalVC = ST_FinalST_PushPeculiarityViewController()
            
            finalVC.pictures = images.map({ (id,img) -> UIImage in
                return img
            })
            
            self?.navigationController?.pushViewController(finalVC)
        }
        
        vc.picker_video_closure = {[weak self] url,seconds in
            
            let filename = UUID().uuidString+".mp4"
            
            guard var videoPath = SC.push_peculiarity_directory else { return }
            
            videoPath.appendPathComponent(filename)
            
            do {
                try FileManager.default.copyItem(at: url, to: videoPath)
            } catch (let error) {
                print("Cannot copy item at \(url) to \(videoPath): \(error)")
                return
            }
            
            let finalVC = ST_FinalST_PushPeculiarityViewController()
            
            finalVC.videoURL = videoPath
            
            self?.navigationController?.pushViewController(finalVC)
            
            
        }
        
        GlobalPresent(toController: vc)
        
    }
    
    @objc func photo_btn_click(){
        
        /*
        let vc = ST_PEImagePickerController()
        
        vc.picker_style = .image
        
        GlobalPresent(toController: vc)
        */
        
        picker_media_handle(imageType: true)
        
        
    }
    @objc func record_btn_click(){
        
        picker_media_handle(imageType: false)
        /*
        let vc = ST_RGCameraController()
                
            vc.completeActionBlock = {[weak self] url, type in

                let finalVC = ST_FinalST_PushPeculiarityViewController()
                
                if type == .video {
                   
                    let srcURL = URL.init(fileURLWithPath: url)
                    
                    let filename = UUID().uuidString+".mp4"
                    
                    guard var videoPath = SC.push_peculiarity_directory else { return }
                    
                    videoPath.appendPathComponent(filename)
                    
                    do {
                        try FileManager.default.copyItem(at: srcURL, to: videoPath)
                    } catch (let error) {
                        print("Cannot copy item at \(url) to \(videoPath): \(error)")
                        return
                    }
                    
                    finalVC.videoURL = videoPath
                    
                }//如果是图片
                else if type == .image{
                    
                    if let originalImage = UIImage.init(contentsOfFile: url){
                        
//                        print("BUG拍图-originalImage.size:",originalImage.size)
                        
//                        let thumbnailImage = originalImage.resize_image(targetWidth: 140)
                        
//                        finalVC.picture = originalImage
                        
                        finalVC.pictures = [originalImage]
                        
                    }
                }
                
                self?.navigationController?.pushViewController(finalVC)
                
            }
     
            vc.modalPresentationStyle = .fullScreen
        
        
            GlobalPresent(toController: vc, animated: true)
 
         */
    }
}
